package com.example.demo.leetcode.classics150;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _86二叉搜索树的最小绝对差
 * @description
 * @date 2023/08/05 8:50
 * <p>
 * ******************************************************
 */
public class _86二叉搜索树的最小绝对差 {

    public int getMinimumDifference(TreeNode root) {
        List<Integer> in = new ArrayList<>();
        inOrder(root, in);
        int min = Integer.MAX_VALUE;
        for (int i = 1; i < in.size(); i++) {
            min = Math.min(min, Math.abs(in.get(i) - in.get(i - 1)));
        }
        return min;
    }

    private void inOrder(TreeNode root, List<Integer> in) {
        if (root == null) {
            return;
        }
        if (root.left != null) {
            inOrder(root.left, in);
        }
        in.add(root.val);
        if (root.right != null) {
            inOrder(root.right, in);
        }
    }


    int res = Integer.MAX_VALUE;
    int pre = -1;
    private void inOrder1(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left != null) {
            inOrder1(root.left);
        }
        if (pre != -1) {
            res = Math.min(res, Math.abs(pre - root.val));
        }
        pre = root.val;
        if (root.right != null) {
            inOrder1(root.right);
        }
    }
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
